import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilters } from './common/filters/httpException.filters';
import { ResponseInterceptor } from './common/interceptor/response.interceptor';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import { ValidationPipe } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';
import { corsConfig, sysBase } from '@/utils/config';
import { JwtAuthGuard } from './modules/auth/jwtAuth.guard';
import * as compression from 'compression';

//跨域设置
//中间件日志记录
//token鉴权也可以在这里做
//白名单
const whiteList = ["/list"]
//全局中间件
function MiddlewareAll (req: Request, res: Response, next:NextFunction): any {
  let headerArr = req.rawHeaders

  let token = ""
  for(let i in headerArr){
    if(headerArr[i].indexOf("Bearer ") >= 0){
      token = headerArr[i].split("Bearer ")[1]
      break;
    }
  }
  next()
  console.log('我经过了全局中间件');
  // if(whiteList.includes(req.originalUrl)){
  //   next()
  // }else{
  //   res.send({message:"不让你访问"})
  // }
}

// nest-status-monitor
// node中如何使用Nest.js实现简易版请求监控
async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  //compression插件挂载
  //相应数据发送到客户端之前对其进行压缩，有助于减少数据大小并缩短响应时间
  app.use(compression())

  const config = new DocumentBuilder()
    .setTitle('vue_vite_ts')
    .setDescription('沉默小管管理系统')
    .setVersion('1.0')
    .addTag('vue')
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup('api', app, document);

  app.enableCors(corsConfig)//设置跨域

  // app.use(MiddlewareAll)//全局中间件使用

  //鉴权 守卫
  app.useGlobalGuards(new JwtAuthGuard(app))

  app.useGlobalInterceptors(new ResponseInterceptor());//全局拦截器

  //全局管道校验
  app.useGlobalPipes(new ValidationPipe({
    transform:true,//自动变换
  }))

  app.useGlobalFilters(new HttpExceptionFilters(app));//全局过滤 异常过滤器

  await app.listen(sysBase.port);
  
}
bootstrap().then(()=>{
  console.log(`http://localhost:${sysBase.port}`);
});
